package com.example.joblinker.controller;

import com.example.joblinker.common.Result;
import com.example.joblinker.entity.Resume;
import com.example.joblinker.service.ResumeService;
import com.example.joblinker.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/resumes")
public class ResumeController {

    @Autowired
    private ResumeService resumeService;
    
    @Autowired
    private UserService userService;

    @GetMapping
    public Result<List<Resume>> getResumeList(@RequestAttribute Long userId) {
        List<Resume> resumes = resumeService.getResumeList(userId);
        return Result.success(resumes);
    }

    @GetMapping("/{resumeId}")
    public Result<Resume> getResumeDetail(@PathVariable Long resumeId, @RequestAttribute Long userId) {
        try {
            // 获取用户角色
            String userRole = userService.getUserRole(userId);
            
            Resume resume;
            // 如果是HR或管理员，直接查询简历
            if ("ROLE_HR".equals(userRole) || "ROLE_ADMIN".equals(userRole)) {
                resume = resumeService.getResumeById(resumeId);
            } else {
                // 如果是普通用户，只能查看自己的简历
                resume = resumeService.getResumeDetail(resumeId, userId);
            }
            
            if (resume == null) {
                return Result.error("简历不存在");
            }
            return Result.success(resume);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping
    public Result<Resume> createResume(@RequestBody Resume resume, @RequestAttribute Long userId) {
        resume.setUserId(userId);
        Resume created = resumeService.createResume(resume);
        return Result.success(created);
    }

    @PutMapping("/{id}")
    public Result<Void> updateResume(@PathVariable Long id, @RequestBody Resume resume, @RequestAttribute Long userId) {
        resume.setId(id);
        resume.setUserId(userId);
        boolean success = resumeService.updateResume(resume);
        return success ? Result.success() : Result.error("更新失败");
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteResume(@PathVariable Long id, @RequestAttribute Long userId) {
        boolean success = resumeService.deleteResume(id, userId);
        return success ? Result.success() : Result.error("删除失败");
    }

    @PutMapping("/{id}/default")
    public Result<Void> setDefaultResume(@PathVariable Long id, @RequestAttribute Long userId) {
        boolean success = resumeService.setDefaultResume(id, userId);
        return success ? Result.success() : Result.error("设置默认简历失败");
    }
} 